var _key = 1;
let arr = [{
    roomName: '测试房间',
    createUserKey: 'admin',
    createUserName: 'admin',
    key: -999,
    imageUrl: 'http://image.fengyitong.name/Blog%2F20170927%2F9885883_122140091001_2',
    personList: [],
    createTime: new Date(),
    drawInfoList: []
}];




module.exports = {
    getRoomList() {
        var ar = arr.map(t => {
            return {
                roomName: t.roomName,
                createUserKey: t.createUserKey,
                createUserName: t.createUserName,
                key: t.key,
                imageUrl: t.imageUrl,
                personList: t.personList,
                createTime: t.createTime,
                drawInfoList: [],
            }
        });
        return ar;
    },
    addRoom(roomName, user) {

        var obj = {
            roomName: roomName,
            createUserKey: user.key,
            createUserName: user.userName,
            key: ++_key,
            imageUrl: 'http://image.fengyitong.name/Blog%2F20170927%2F9885883_122140091001_2',
            personList: [user],
            createTime: new Date(),
            drawInfoList: []
        };
        user.roomKey = _key;
        arr.unshift(obj);
        return obj;
    },
    removeRoom(key, user) {
        for (let i = 0; i < arr.length; i++) {
            const item = arr[i];
            if (item.key == key) {
                if(this.checkDelRoom(item,user)){
                    arr.splice(i, 1);
                    return true;
                }else{
                    return false;
                }
            }
        }
        return false;
    },
    checkDelRoom(room,user){
        if(room.personList.length > 1) return false;
        for (const person of room.personList) {
            if(person.key !== user.key){
                return false;
            }
        }
        return true;
    },
    getRoomInfo(key) {
        var model = arr.find(t => {
            return t.key == key;
        });
        return model;
    },
    addPerson(room, user) {
        if (!room) return;
        var model = room.personList.find(t => {
            return t.key == user.key;
        });
        if (model) {
            model.userName = user.userName;
        } else {
            room.personList.push(user);
        }
        user.roomKey = room.key;
    },
    leaveRoom(user) {
        if (user && user.roomKey != null) {
            var room = this.getRoomInfo(user.roomKey);
            this.removePerson(room, user.key);
            user.roomKey = undefined;
            return room;
        }
        return null;
    },
    removePerson(room, key) {
        if (!room) return;
        for (let i = 0; i < room.personList.length; i++) {
            const user = room.personList[i];
            if (key == user.key) {
                room.personList.splice(i, 1);
                return true;
            }
        }
        return false;
    }
};